<?php
namespace Systemht\Model;
use Think\Model;
class CateModel extends Model{
	protected $insertField = array('name','en_name','parent_id','type','content','sort','comment');
	protected $updateField = array('id','old_image','name','type','en_name','parent_id','content','sort','comment');
	protected $_validate = array(
		array('name','require','栏目名称不能为空'),
		);
	protected function _before_insert(&$data,$option){
		$data['ctime'] = time();
		if(isset($_FILES['image']) && $_FILES['image']['error'] == 0){
            $data['image'] = uploadImage('image');
        }
	}
	protected function _before_update(&$data,$option){
		if(isset($_FILES['image']) && $_FILES['image']['error'] == 0){
            $data['image'] = uploadImage('image');
            delImage(I('post.old_image'));
        }
	}
	//获去树状图
	public function getTree(){
		$data = $this->order('sort ASC')->select();
		return $this->tree($data);
	}
    //获取文章分类
    public function getArcCate(){
        $data = $this->where(array('type'=>array('neq',2)))->select();
        return $this->tree($data);
    }
	//生成树状结构
	private  function tree($data, $pid=0, $level=0){
        static $tree = array();
        foreach($data as $v){
            if($pid == $v['parent_id']){
                $v['level'] = $level;
                $tree[] = $v;
                $this->tree($data, $v['id'],$level+1);
            }
        }
        return $tree;
    }

    //前台栏目结构
    public function getCate($pid = 0){
    	$data = $this->where(array('status'=>1))->order('sort ASC')->select();
    	//找出一级分类
    	foreach ($data as $key => $value) {
    		if($value['parent_id'] == $pid){
    			//找出二级分类
    			foreach ($data as $k => $v) {
    				if($v['parent_id'] == $value['id']){
                        //找出三级分类
                        // foreach($data as $k1 => $v1){
                        //     if($v1['parent_id'] == $v['id']){
                        //         $v['children'][] = $v1;
                        //     }
                        // }
    					$value['children'][] = $v;
    				}
    			}
    			$cate[] = $value;
    		}
    	}
    	return $cate;
    }

    //获取栏目所有三级分类id
    public function getCateId($pid = 0){
        $data = $this->select();
        //找出二级分类
        $arr[] = $pid;
        foreach ($data as $value) {
            if($value['parent_id'] == $pid){
                //找出三级分类
                foreach ($data as $v) {
                    if($v['parent_id'] == $value['id']){
                        $arr[] = $v['id'];
                    }
                }
                $arr[] = $value['id'];
            }
        }
        return $arr;
    }
}